{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Iterable是可迭代\n",
    "Iterator是迭代器"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "True\n",
      "False\n",
      "True\n"
     ]
    }
   ],
   "source": [
    "from collections.abc import Iterable, Iterator\n",
    "\n",
    "a = [1, 2, 3]\n",
    "print(isinstance(a, Iterable))  # True\n",
    "print(isinstance(a, Iterator))  # False\n",
    "iter_a = iter(a)\n",
    "print(isinstance(iter_a, Iterable))  # True"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [],
   "source": [
    "class Company:\n",
    "    def __init__(self, employees):\n",
    "        self.employees = employees\n",
    "    def __iter__(self):\n",
    "        print(self)\n",
    "        return MyIterator(self.employees)\n",
    "    # def __getitem__(self, index):\n",
    "    #     # print(index)\n",
    "    #     return self.employees[index]\n",
    "\n",
    "# python是基于协议来做的，不用继承也行，只要实现方法就行\n",
    "# class MyIterator:\n",
    "    \n",
    "class MyIterator(Iterator):\n",
    "    def __init__(self, company_list):\n",
    "        self.iter_list = company_list\n",
    "        self.index = 0\n",
    "    # 不要放在普通的类里实现，单独实现一个迭代器来维护index\n",
    "    def __next__(self):\n",
    "        if self.index >= len(self.iter_list):\n",
    "            raise StopIteration\n",
    "        item = self.iter_list[self.index]\n",
    "        self.index += 1\n",
    "        return item"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "<__main__.Company object at 0x000001CBDB603170>\n",
      "John\n",
      "Mary\n",
      "Tom\n"
     ]
    }
   ],
   "source": [
    "company = Company([\"John\", \"Mary\", \"Tom\"])\n",
    "for i in company:\n",
    "    print(i)"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "grammer-study-12-env",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.12.4"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
